package schema

import (

	"net/http"
	"github.com/go-xorm/xorm"
// pq driver
	_ "github.com/lib/pq"
)

func JoindQuery(eng *xorm.Engine, r *http.Request,
fields []string, rows interface{}, ob interface{},extend [][]string) int64 {
	qc := &QueryConf{}
	decoder := NewDecoder()
	r.ParseMultipartForm(200000000)
	err := decoder.Decode(qc, r.Form)
	if err!=nil{
		return 0
	}
	sess := eng.AllCols()
	for  i:=0;i<len(extend);i++{
		sess.Join(extend[i][0], extend[i][1], extend[i][2])
	}
	if qc.Oseq >-1 {
		if qc.Odir == "a" {
			sess = sess.Asc(fields[qc.Oseq])
		} else {
			sess = sess.Desc(fields[qc.Oseq])
		}
	}

	if qc.Qseq[0] < 0 {
		err := sess.Limit(qc.PgSize, qc.Start).Find(rows)
		if err!=nil{
			return 0
		}
		count, err := sess.Count(ob)
		return count

	}
	var ws, vs string
	for i:=0;i<len(qc.Qverb);i++{
		switch qc.Qverb[i][0] {
		case 'k': // like

			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", "%"+qc.Qpt[i]+"%"

		case 'p': // prefix
			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", qc.Qpt[i]+"%"
		case 's': // suffix
			ws, vs = fields[qc.Qseq[i]]+" LIKE ? ", "%"+qc.Qpt[i]
		case 'e': // equal
			ws, vs = fields[qc.Qseq[i]]+"=?", qc.Qpt[i]
		case 'g': // greater than
			ws, vs = fields[qc.Qseq[i]]+">?", qc.Qpt[i]
		case 'l': // less than
			ws, vs = fields[qc.Qseq[i]]+"<?", qc.Qpt[i]
		}
		if i==0{
			sess = sess.Where(ws, vs)
		}else{
			sess = sess.And(ws, vs)
		}

	}
	err = sess.Limit(qc.PgSize, qc.Start).Find(rows)


	if err != nil {
		return 0

	}

	count, err := sess.Count(ob)

	if err != nil {
		return 0

	}

	return count

}
